package com.dayuanit.service.impl;
import java.sql.Connection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.SqlSession;

import com.dayuanit.domain.Detail;
import com.dayuanit.domain.User;
import com.dayuanit.service.UserService;
import com.dayuanit.util.DateBaseUtil;

public class UserServiceImpl implements UserService{

	public void openAccount(String username, String cardNum, int amount) {
		
		SqlSession session = DateBaseUtil.getSqlSession(false);
		
		//由于connection是共享的，防止自动提交关闭，这里手动设置为true
		
		try {
			User user = new User();
			user.username = username;
			user.cardNum = cardNum;
			user.balance = amount;
			
			int id = session.insert("com.dayuanit.domain.addUser", user);
			if (id == 0) {
				System.out.println("open account failed");
				session.rollback();
				return;
			}

			user.id = id;

			//记录流水
			Detail detail = new Detail();
			detail.userId = user.id;
			detail.amount = amount;
			detail.cardNum = user.cardNum;
			detail.descMsg = "开户存钱";

			
			int rows = session.insert("com.dayuanit.domain.addDetail", detail);
			if (0 == rows) {
				System.out.println("open account deposit failed");
				session.rollback();
				return;
			}

			session.commit();

		} catch(Exception e) {
			e.printStackTrace();
			session.rollback();
		} finally {
			if (null != session) {
				session.close();
			}
		}
		
	}

	public void deposit(String cardNum, int amount) {

		SqlSession session = DateBaseUtil.getSqlSession(false);
		//存钱需要先更新余额 再插入流水 需要提供事物，将自动提交改为手动提交
		try {
			
			User user = session.selectOne("com.dayuanit.domain.queryUser", cardNum);
			int oldBalance = user.balance;
			
			user.balance += amount;
			
			Map<String , Object> map = new HashMap<String , Object>();
			map.put("newBalance", user.balance);
			map.put("id",  user.id);
			map.put("oldBalance", oldBalance);
			
			
			int rows = session.update("com.dayuanit.domain.modifyBalance", map);
			if (1 != rows) {
				System.out.println("deposit update balance failed");
				session.rollback();
				return;
			}

			//记录存钱流水
			Detail detail = new Detail();
			detail.userId = user.id;
			detail.amount = amount;
			detail.cardNum = user.cardNum;
			detail.descMsg = "存钱";

			
			session.insert("com.dayuanit.domain.addDetail", detail);

			session.commit();

		}catch(Exception e) {
			session.rollback();
			e.printStackTrace();
			
		} finally {
			if (null != session) {
				session.close();
			}
		}

	}

	public void draw(String cardNum, int amount) {
		SqlSession session = DateBaseUtil.getSqlSession(false);
		//取钱需要先更新余额 再插入流水 需要提供事物，将自动提交改为手动提交
		try {
			
			User user = session.selectOne("com.dayuanit.domain.queryUser", cardNum);
			int oldBalance = user.balance;
			
			user.balance -= amount;
			
			Map<String , Object> map = new HashMap<String , Object>();
			map.put("newBalance", user.balance);
			map.put("id",  user.id);
			map.put("oldBalance", oldBalance);
			if(user.balance<0){
				System.out.println("余额不足");
				return;
			}
			
			int rows = session.update("com.dayuanit.domain.modifyBalance", map);
			if (1 != rows) {
				System.out.println("deposit update balance failed");
				session.rollback();
				return;
			}

			//记录取钱流水
			Detail detail = new Detail();
			detail.userId = user.id;
			detail.amount = amount;
			detail.cardNum = user.cardNum;
			detail.descMsg = "取钱";

			
			session.insert("com.dayuanit.domain.addDetail", detail);

			session.commit();

		}catch(Exception e) {
			session.rollback();
			e.printStackTrace();
			
		} finally {
			if (null != session) {
				session.close();
			}
		}

	}

	
	public void transfer(String inCardNum, String outCardNum, int amount) {

		if ( 0 >= amount) {
			System.out.println("金额不合法");
			return;
		}
		
		SqlSession session = DateBaseUtil.getSqlSession(false);

		//TODO 根据卡号查询目标用户
		User inUser = session.selectOne("com.dayuanit.domain.queryUser", inCardNum);
		if (null == inUser) {
			System.out.println("查无此人");
			return;
		}

		//TODO 减去自己的金额
		User outUser = session.selectOne("com.dayuanit.domain.queryUser", outCardNum);
		
		if (null == outUser) {
			System.out.println("查无此人");
			return;
		}
		
		int oldOutBalance = outUser.balance;
		int oldInBalance = inUser.balance;

		outUser.balance -= amount;

		if (outUser.balance < 0) {
			System.out.println(Thread.currentThread().getName()  + "余额不足");
			return;
		}

		try {

			System.out.println(Thread.currentThread().getName() + "正在转账");
			
			Map<String , Object> map = new HashMap<String , Object>();
			map.put("newBalance", outUser.balance);
			map.put("id",  outUser.id);
			map.put("oldBalance", oldOutBalance);
			
			
			int rows = session.update("com.dayuanit.domain.modifyBalance", map);
			if (rows == 0) {
				System.out.println(Thread.currentThread().getName() + "转账失败");
				session.rollback();
				return;
			}
			
			Thread.sleep(10 * 1000);
			System.out.println(Thread.currentThread().getName() + "可以转账");

			//TODO 增加目标金额
			inUser.balance += amount;
			
			map.put("newBalance", inUser.balance);
			map.put("id",  inUser.id);
			map.put("oldBalance", oldInBalance);
			
			rows = session.update("com.dayuanit.domain.modifyBalance", map);
			if (0 == rows) {
				System.out.println(Thread.currentThread().getName() + "转账失败");
				session.rollback();
				return;
			}

			//TODO 增加两个交易流水
			Detail outDetail = new Detail();
			outDetail.userId = outUser.id;
			outDetail.amount = amount;
			outDetail.cardNum = outUser.cardNum;
			outDetail.descMsg = "转账支出";
			
			
			rows = session.insert("com.dayuanit.domain.addDetail", outDetail);
			if (0 == rows) {
				System.out.println("转账失败，流水插入失败");
				session.rollback();
				return;
			}

			Detail inDetail = new Detail();
			inDetail.userId = inUser.id;
			inDetail.amount = amount;
			inDetail.cardNum = inUser.cardNum;
			inDetail.descMsg = "转账收入";
			
			rows = session.insert("com.dayuanit.domain.addDetail", inDetail);
			if (0 == rows) {
				System.out.println("转账失败，流水插入失败");
				session.rollback();
				return;
			}

			session.commit();
			
		} catch(Exception e) {
			session.rollback();
			e.printStackTrace();
		} finally {
			if (null != session) {
				session.close();
			}
		}

	}

	public void queryBalance(String cardNum) {
		SqlSession session = DateBaseUtil.getSqlSession(false);
		User User = session.selectOne("com.dayuanit.domain.queryUser", cardNum);
		if (null == User) {
			System.out.println("查无此人，请重新输入CardNum");
			return ;
		}
		System.out.println("卡号："+User.cardNum+"  "+"当前余额为："+User.balance);
		
	}

	public void queryDetails(String cardNum) {
		SqlSession session = DateBaseUtil.getSqlSession(false);
		List<Detail> list = session.selectList("com.dayuanit.domain.queryDetail",cardNum);	
		if(list.size()==0){
			System.out.println("查无此人,请重新输入CardNum");
			return ;
		}
		for(Detail detail :list){
			System.out.println(detail);
		}		

	}

}